package com.jojo.tool;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author BigPigMan
 * @description
 * @date 2021/4/29 17:54
 */
@Component
public class GeneratorExecuter {

    @Autowired
    private GeneratorConfig config;

    private GlobalConfig getGlobalConfig() {
        GlobalConfig gc = new GlobalConfig();
        gc.setDateType(DateType.ONLY_DATE);
        gc.setIdType(IdType.ID_WORKER);
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/tmp/src/main/java");
        gc.setAuthor("JOJO");
        gc.setOpen(true);
        // service 命名方式
        gc.setServiceName("%sService");
        gc.setControllerName("%sController");
        // service impl 命名方式
        gc.setServiceImplName("%sServiceImpl");
        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        // XML 二级缓存
        gc.setEnableCache(false);
        // XML ResultMap
        gc.setBaseResultMap(true);
        // XML columList
        gc.setBaseColumnList(true);
        return gc;
    }

    private DataSourceConfig getDataSourceConfig(String dbUrl, String dbName, String userName, String password) {
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://" + dbUrl + "/" + dbName
                + "?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai"); // 位置 1
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(userName);
        dsc.setPassword(password);
        return dsc;
    }

    private PackageConfig getPackageConfig(String parentPackage, String entityPackageName, String mapperPackageName, String servicePackageName) {
        PackageConfig pc = new PackageConfig();
        pc.setParent(parentPackage);
        pc.setEntity(entityPackageName);
        pc.setMapper(mapperPackageName);
        pc.setService(servicePackageName);
        pc.setServiceImpl(servicePackageName + ".impl");
        return pc;
    }

    private InjectionConfig getInjectionConfig() {
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        cfg.setFileOutConfigList(focList);
        return cfg;
    }

    // 策略配置
    private StrategyConfig getStrategyConfig(String logicField) {
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        // 设置逻辑删除键
        strategy.setLogicDeleteFieldName(logicField);

        // 驼峰转连字符
        strategy.setControllerMappingHyphenStyle(true);
        return strategy;
    }

    public void run() {
        // 公共设置
        GeneratorExecuter generatorSetting = new GeneratorExecuter();
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = generatorSetting.getGlobalConfig();
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = generatorSetting.getDataSourceConfig(config.getUrl(), config.getDbName(), config.getUserName(), config.getPassword());
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = generatorSetting.getPackageConfig(config.getParentPackageName(), config.getEntityPackageName(), config.getMapperPackageName(), config.getServicePackageName());
        mpg.setPackageInfo(pc);
        // 自定义配置
        InjectionConfig cfg = generatorSetting.getInjectionConfig();

        // 不需要设置为null , 不生成
        mpg.setTemplate(new TemplateConfig()
                .setXml(null)
                .setController(null)
        );
        StrategyConfig strategy2 = generatorSetting.getStrategyConfig(config.getLogicFieldName());
        mpg.setStrategy(strategy2);
        // 选择 freemarker 引擎需要指定如下加，注意 pom 依赖必须有！
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        String projectPath = System.getProperty("user.dir");

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/tmp/src/main/xml/"
                        + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);


        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass(config.getSuperEntityClass());
        List<String> superEntityColumns = config.getSuperEntityColumns();
        if (superEntityColumns != null && superEntityColumns.size() > 0) {
            String[] superColumnArr = superEntityColumns.toArray(new String[superEntityColumns.size()]);
            strategy.setSuperEntityColumns(superColumnArr);
        }
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
//        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        String includeTable = config.getIncludeTable();
        if (StringUtils.isNotBlank(includeTable)) {
            if (!"*".equals(includeTable)) {
                strategy.setInclude(includeTable.split(","));
            }
        }
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(config.getTablePreffix() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}
